package com.monolith.jd.demo.ws;

import com.monolith.jd.demo.ws.cache.WebsocketSessionCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * 2018/10/9 Create by 郭文梁
 * NewMessageNotifier
 * 文本数据处理器
 *
 * @author 郭文梁
 * @date 2018/10/9
 */
@Component
@Slf4j
public class NewMessageNotifier extends TextWebSocketHandler {
    private final WebsocketSessionCache sessionCache;
    private int sessionKey;

    @Autowired
    public NewMessageNotifier(WebsocketSessionCache sessionCache) {
        this.sessionCache = sessionCache;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        sessionKey = sessionCache.addSession(session);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        WebSocketSession removedSession = sessionCache.removeSession(sessionKey);
        if (session != removedSession) {
            log.warn("The removed session does not match the closed session for key [{}]", sessionKey);
        }
    }
}
